import { splitProps, createMemo, Index } from "solid-js";
import type { TableFooterProps } from "./types";
import { hasNumberWidth } from "./utils";

const TableFooter = <T extends {}>(p: TableFooterProps<T>) => {
    const [local] = splitProps(p, ["classList", "columns", "datas", "style"]);

    const hasFooter = createMemo(() => {
        return (
            (local.datas?.length ?? 0) > 0 &&
            (local.columns?.filter((col) => col?.footer !== undefined)?.length ?? 0) >
            0
        );
    });

    const mapped = createMemo(() => {
        return local.columns?.map((col) => {
            const has = hasNumberWidth(col);
 
            return {
                ...col,
                classList: {
                    "text-start": (col.align ?? col.headerAlign) === "start",
                    "text-center": (col.align ?? col.headerAlign) === "center",
                    "text-end": (col.align ?? col.headerAlign) === "end",
                    ...col?.classList,
                },
            };
        });
    });

    return (
        hasFooter() && (
            <tfoot classList={local.classList} style={local.style}>
                <tr>
                    <Index each={mapped()}>
                        {(column, index) => {
                            const col = column();
                            return (
                                <td style={col.style} classList={col.classList}>
                                    {col.footer && typeof col.footer === "function"
                                        ? col.footer(local.datas ?? [], col.name!)
                                        : col.footer}
                                </td>
                            );
                        }}
                    </Index>
                </tr>
            </tfoot>
        )
    );
};


export default TableFooter